/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */
define(['adminapp'],function ($app) {
    $app.navactive('service_gift');

    var source = $("#message-template").html();
    var template = Handlebars.compile(source);

    $(function() {
        $app.formvalidator({
            'query': {
                required: true
            },
            'sn': {
                required: true
            }
        }, 'searchform');

        $("#search").click(function () {
            $("#searchform").ajaxSubmit({
                success: callback
            });
        });
    });

    function callback(msg) {
        if (msg.status == "OK") {
            $.each(msg.data, function(k ,v) {
                if (k == 'recv') {
                    if (v) {
                        $('#' + k).html("已领取");
                        $('#save').hide();
                    } else {
                        $('#' + k).html("未领取");
                        $('#save').show();
                    }
                } else if (k == 'recordId') {
                    $('#save').attr("recordId", v);
                } else {
                    $('#' + k).html(v);
                }
            });
            $("#tip-body").html("");
        } else {
            $(".fieldInfo").html("");
            var context = {class : "alert-warning", message : msg.message};
            $("#tip-body").html(template(context));
            $('#save').attr("recordId", "");
            $('#save').hide();
        }
    }

    $("#save").click(function(){
        var recordId = $(this).attr("recordId");
        if (recordId) {
            $.post(g.ctx + 'customer/gift/receive', {recordId:recordId}, function(msg) {
                if (msg.status == "OK") {
                    var context = {class : "alert-success", message : msg.message};
                    $("#tip-body").html(template(context));
                    $('#save').attr("recordId", "");
                    $('#recv').html("已领取");
                    $('#save').hide();
                } else {
                    var context = {class : "alert-warning", message : msg.message};
                    $("#tip-body").html(template(context));
                }
            });
        }
    });
});